import IO from 'koa-socket';
import Koa from 'koa';
import { historyApiFallback } from 'koa2-connect-history-api-fallback';
import cors from 'koa2-cors';
import Cookies from 'cookies';
import httpError from 'http-errors';
import router from './router';
import bodyParser from 'koa-bodyparser';
import db from './mongodb/db';

const app = new Koa();
app
  .use(bodyParser())
  // 配置跨域
  .use(cors())
  // 配合前端vue项目history路由模式
  .use(historyApiFallback())
  // 响应用户请求
  .use(router.routes()).use(router.allowedMethods());


const port = 3000;

const io = new IO()

// 将socket与koa实例相关联
io.attach(app)


// logger

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${ctx.method} ${ctx.url}-${rt}`);
});

// x-response-time

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// error

app.on('error', (err, ctx) => {
  log.error('server error', err, ctx)
});

// connection
io.on('conection', (socket) => {
  console.log(socket)
  console.log('socket已连接')
  io.broadcast('online', socket.data)
});

io.on('join', (ctx, data) => {
  console.log(ctx, data)
})

// 接收消息
io.on('sendMsg', ctx => {
  // 广播，所有人消息
  io.broadcast('response', ctx.data)
})

app.listen(port, () => {
  console.log(`service start，open browser localhost:${port}`)
});